<template>
  <div class="write-article-container">
    <div class="bg-container">
      <div class="bg-dot"></div>
      <div class="bg-dot dot-2"></div>
      <div class="bg-dot dot-3"></div>
    </div>
    <div class="article-form">
      <div class="form-left card-container">
        <h2 class="section-title">{{ isEdit ? '修改文章' : '写文章' }}</h2>
        <div class="form-group">
          <label for="title">文章标题</label>
          <input type="text" id="title" v-model="article.title" placeholder="请输入文章标题">
        </div>
        <div class="form-group">
          <label for="coverImage">文章封面</label>
          <input type="file" id="coverImage" @change="handleCoverImageChange">
        </div>
        <div class="form-group">
          <label for="introduction">文章简介</label>
          <textarea id="introduction" v-model="article.introduction" placeholder="请输入文章简介"></textarea>
        </div>
        <div class="form-group">
          <label for="tags">标签</label>
          <input type="text" id="tags" v-model="article.tag" placeholder="多个标签用逗号分隔">
        </div>
        <div class="button-group">
          <el-button type="primary" @click="saveDraft">保存草稿</el-button>
          <el-button type="warning" @click="publishArticle">发布文章</el-button>
        </div>
      </div>
      <div class="form-right">
        <v-md-editor v-model="article.content" height="100%"></v-md-editor>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import VueMarkdownEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';

VueMarkdownEditor.use(vuepressTheme);

export default {
  components: {
    'v-md-editor': VueMarkdownEditor
  },
  data() {
    return {
      article: {
        title: '',
        coverImage: null,
        introduction: '',
        tag: '',
        content: ''
      },
      coverImageFile: null,
      isEdit: false
    };
  },
  async mounted() {
    const articleId = this.$route.params.id;
    if (articleId) {
      this.isEdit = true;
      try {
        // 获取文章详情
        const articleResponse = await axios.get(`/article/detail/${articleId}`);
        if (articleResponse.data.code === 200) {
          this.article = articleResponse.data.data;
          // 获取文章内容
          const markdownResponse = await axios.get(this.article.content);
          this.article.content = markdownResponse.data;
        }
      } catch (error) {
        console.error('文章信息加载失败', error);
        this.$message.error('文章信息加载失败');
      }
    }
  },
  methods: {
    handleCoverImageChange(event) {
      this.coverImageFile = event.target.files[0];
    },
    async saveDraft() {
      try {
        const formData = new FormData();
        // 分别添加文章的各个字段，但排除 coverImage
        const keysToAdd = Object.keys(this.article).filter(key => key!== 'coverImage');
        keysToAdd.forEach(key => {
          formData.append(key, this.article[key]);
        });
        // 只有当选择了封面图片时才添加到 formData 中
        if (this.coverImageFile) {
          formData.append('coverImage', this.coverImageFile);
        }
        const markdownBlob = new Blob([this.article.content], { type: 'text/markdown' });
        formData.append('markdownFile', markdownBlob, 'article.md');

        // 打印 FormData 中的内容，用于调试
        for (let pair of formData.entries()) {
          console.log(pair[0]+ ', ' + pair[1]); 
        }

        const url = this.isEdit ? '/article/update' : '/article/saveDraft';
        const response = await axios.post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        if (response.data.code === 200) {
          this.$message.success('草稿保存成功');
        } else {
          this.$message.error('草稿保存失败');
        }
      } catch (error) {
        console.error('草稿保存失败', error);
        this.$message.error('草稿保存失败');
      }
    },
    async publishArticle() {
      try {
        const formData = new FormData();
        // 分别添加文章的各个字段，但排除 coverImage
        const keysToAdd = Object.keys(this.article).filter(key => key!== 'coverImage');
        keysToAdd.forEach(key => {
          formData.append(key, this.article[key]);
        });
        // 只有当选择了封面图片时才添加到 formData 中
        if (this.coverImageFile) {
          formData.append('coverImage', this.coverImageFile);
        }
        const markdownBlob = new Blob([this.article.content], { type: 'text/markdown' });
        formData.append('markdownFile', markdownBlob, 'article.md');

        // 打印 FormData 中的内容，用于调试
        for (let pair of formData.entries()) {
          console.log(pair[0]+ ', ' + pair[1]); 
        }

        const url = this.isEdit ? '/article/update' : '/article/create';
        const response = await axios.post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        if (response.data.code === 200) {
          this.$message.success('文章发布成功');
        } else {
          this.$message.error('文章发布失败');
        }
      } catch (error) {
        console.error('文章发布失败', error);
        this.$message.error('文章发布失败');
      }
    }
  }
};
</script>

<style scoped>
.write-article-container {
  display: flex;
  min-height: 100vh;
  /* background: #f4f4f4; */
  position: relative;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

.bg-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  overflow: hidden;
}

.bg-dot {
  position: absolute;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ffb76b, #ff7c00);
  opacity: 0.1;
  animation: float 6s infinite ease-in-out;
  filter: blur(2px);
}

.dot-2 {
  right: 10%;
  bottom: 15%;
  width: 80px;
  height: 80px;
  animation-delay: -2s;
  animation-duration: 8s;
}

.dot-3 {
  left: 20%;
  top: 70%;
  width: 100px;
  height: 100px;
  animation-delay: -3s;
  animation-duration: 10s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-30px) rotate(5deg);
  }
}

.article-form {
  display: flex;
  width: 100%;
  padding: 20px;
  gap: 20px;
}

.form-left {
  flex: 1;
  min-width: 300px;
}

.form-right {
  flex: 3;
}

.card-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(5px);
  border-radius: 20px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
  /* 调整左右内边距 */
  padding: 25px 25px; 
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.button-group {
  display: flex;
  justify-content: space-between;
}

.button-group button {
  border-radius: 24px;
  background: linear-gradient(135deg, #ffb76b, #ff7c00);
  border: none;
  /* 调整按钮高度 */
  height: 40px; 
  /* 调整字体大小 */
  font-size: 14px; 
  /* 调整左右内边距 */
  padding: 0 20px; 
  transition: all 0.3s;
  box-shadow: 0 5px 15px rgba(255, 183, 107, 0.3);
  color: white;
}

.button-group button:hover {
  background: linear-gradient(135deg, #ff9d34, #ff6a00);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(255, 157, 52, 0.4);
}
</style>
